<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    //上传图片
    public function image(Request $request)
    {
        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $disk = Storage::disk('image');
            $photo = $request->file('image');
            $realPath = $photo->getRealPath();//临时文件路径
            $name = hash_file('md5', $realPath);
            $time = date('Y-m-d');
            $fileName = '/uploads/image/' . $time . '/' . $name . '.' . $photo->getClientOriginalExtension();
            $bool = $disk->put($fileName, file_get_contents($realPath));
            // 判断是否上传成功 env('APP_URL').
            if ($bool) {
                return $this->returnJson(0, ['path' => $fileName]);
            }
        }
        return $this->returnJson(1, null, '上传图片失败');
        try {

        } catch (\Throwable $e) {
            return $this->returnJson(1, null, $e->getMessage());
        }
    }

    //上传文件
    public function file(Request $request)
    {
        try {
            if ($request->hasFile('file') && $request->file('file')->isValid()) {
                $disk = Storage::disk('file');
                $photo = $request->file('file');
                $realPath = $photo->getRealPath();//临时文件路径
                $name = $photo->getClientOriginalName();
                $time = date('Y-m-d');
                $fileName = '/uploads/file/' . $time . '/' . $name;
                $bool = $disk->put($fileName, file_get_contents($realPath));
                // 判断是否上传成功
                if ($bool) {
                    return $this->returnJson(0, ['path' => $fileName]);
                }
            }
            return $this->returnJson(1, null, '上传文件失败');
        } catch (\Throwable $e) {
            return $this->returnJson(1, null, $e->getMessage());
        }
    }

}
